<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-10-18
 * Time: 下午5:40
 * Token
 */
namespace DB;

use Common\Logger;

class Token extends RedisDefault{
  private $token;

  public function getToken(){
    return $this->token;
  }

  public function get(string $key):?string {
    $redis = self::getInstance();
    if (($val = $redis->get($key)) == false){
      return null;
    }
    return $val;
  }

  /**
   * 初始化token的值
   * @param string $uid 用户id
   * @param int $device 设备号
   */
  public function initByUid(string $uid,int $device = 0){
    $token = md5(mt_rand(100,999).$uid.$device.time());
    $this->initSetTokenByUid($uid,$token,1*3600);
  }

  private function initSetTokenByUid(string $uid, string $token,int $timeout = 1*3600){
    $redis = self::getInstance();
    $old_token = $redis->get($uid);
    if ($old_token != false){
      $redis->delete($uid);
      $redis->delete($old_token);
    }
    $redis->setex($uid,$timeout,$token);
    $redis->setex($token,$timeout,$uid);
    $this->token = $token;
  }
}